<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridProps } from '#/adapter/vxe-table'
import { useTableCURD } from '#/hooks/useTableList'
import { Page } from '@vben/common-ui'
import TableAction from '#/components/TableAction/index.vue'
import { Button, Image, Modal, Textarea, message, UploadDragger } from 'ant-design-vue'
import { ref } from 'vue'
import AddEditModal from './components/AddEditModal.vue'
import { columns, formSchema } from './data/table'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
import accountInfo from '../../views/accountInfo/index.vue'
const formOptions: VbenFormProps = {
    schema: formSchema
}
const gridOptions: VxeGridProps<any> = {
    columns,
    proxyConfig: {
        ajax: {
            query: async ({ page }, formValues) => {
                if (formValues.expireDate) {
                    formValues.startTime = formValues.expireDate[0]
                    formValues.endTime = formValues.expireDate[0]
                    delete formValues.expireDate
                }
                const res = await PageApi.getPageList({
                    ...formValues,
                    ...formValuesObj,
                    limit: page.pageSize,
                    page: page.currentPage
                })
                return {
                    items: res.records,
                    total: res.total
                }
            }
        }
    },
    cellConfig: {
        height: 120
    }
}

/**
 * 表格配置
 */
const {
    Grid,
    reload,
} = useTableCURD<TableListItem>({
    formOptions,
    gridOptions,
    modalOptions: {
        connectedComponent: AddEditModal
    },
    delApi: PageApi.delete
})

const open = ref(false)

/**
 * table 操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            label: '删除',
            popConfirm: {
                title: '确定删除吗？',
                okText: '删除',
                okType: 'danger',
                onConfirm: () => {
                    console.log(record.id)
                    PageApi.delete(record.id).then(res => {
                        if (res) {
                            message.success('删除成功')
                            reload()
                        } else {
                            message.error('删除失败')
                        }
                    })
                }
            }
        }
    ]

    return arr
}
const dlUrl = ref('')
async function handleOk() {
    if (dlUrl.value) {
        let data = [dlUrl.value]
        const res = await PageApi.upload({ urlList: data })
        if (res) {
            message.success('上传成功')
            open.value = false
            reload()
        } else {
            message.error('上传失败')
        }
    } else {
        message.error('请输入API地址')
    }
}
const networkGroupId = ref('') //查看关联账号的id
const networkGroupDetailOpen = ref(false)
async function handleNetworkGroupDetail(id: string) {
    networkGroupId.value = id
    console.log('networkGroupId', networkGroupId.value)
    networkGroupDetailOpen.value = true
}
var formValuesObj = { batchNumber: '' }
// 导入模块
const openDl = ref(false)
const fileList = ref([])
const objFile: any = ref({})
const handleUpload = async (file: any, fileList: any) => {
    fileList = fileList
    objFile.value = file
    return false
}
async function handleOkDl() {
    if (objFile.value?.name) {
        const res = await PageApi.upload2({ file: objFile.value })
        if (res.batchNumber) {
            message.success('上传成功')
            formValuesObj.batchNumber = res.batchNumber
            reload()
            openDl.value = false
        } else {
            message.error('上传失败')
        }
    }
}
</script>

<template>
    <Page>
        <Grid>
            <template #toolbar-tools>
                <view class="flex gap-2">
                    <Button @click="open = true"> API导入动态代理 </Button>
                    <Button type="primary" @click="openDl = true"> 导入代理 </Button>
                    <Button danger type="primary"> 导出代理 </Button>
                </view>
            </template>
            <template #startTime="{ row }"> {{ row.startTime }} - {{ row.endTime }} </template>
            <template #url="{ row }">
                <Image :width="200" :src="row.url" />
            </template>
            <template #action="{ row }">
                <TableAction :actions="getActions(row)" />
            </template>
            <template #isUsed="{ row }">
                {{ row.isUsed ? '是' : '否' }}
            </template>
            <template #networkGroupId="{ row }">
                <Button type="link" @click="handleNetworkGroupDetail(row.id)">查看</Button>
            </template>
        </Grid>
        <Modal v-model:open="open" title="导入" @ok="handleOk">
            <span class="text-red-500">*必填：</span
            ><Textarea v-model:value="dlUrl" placeholder="输入API地址"></Textarea>
        </Modal>
        <Modal v-model:open="networkGroupDetailOpen" width="80%" title="关联账号">
            <accountInfo :id="networkGroupId" :key="networkGroupId" />
        </Modal>
        <Modal v-model:open="openDl" title="导入代理" @ok="handleOkDl">
            <a style="color:#278df2;display: inline-block;" class="pb-3" href="/api/export/template" download="注册导入模版.xlsx">下载模版</a>
            <UploadDragger
                v-model:fileList="fileList"
                name="file"
                :multiple="true"
                :maxCount="1"
                :directory="false"
                :accept="'.xls,.xlsx'"
                :beforeUpload="handleUpload"
            >
                <p class="ant-upload-drag-icon">
                    <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">上传导入文件</p>
                <p class="ant-upload-hint">文件格式xls，xlsx</p>
            </UploadDragger>
        </Modal>
    </Page>
</template>
